package com.ruoyi.system.service.sz.impl;

import java.util.List;

import com.ruoyi.common.core.domain.entity.SisSysOrgan;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.system.domain.sz.*;
import com.ruoyi.system.mapper.sz.*;
import com.ruoyi.system.service.sz.ISzLeaderGroupService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.constant.TimeLineConstants.*;


/**
 * 领导小组&密码办Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-16
 */
@Service
public class SzLeaderGroupServiceImpl implements ISzLeaderGroupService
{
    @Autowired
    private SzLeaderGroupMapper szLeaderGroupMapper;
    @Autowired
    private SzTimeLineMapper szTimeLineMapper;
    @Autowired
    private SzTimeFileMapper szTimeFileMapper;
    @Autowired
    private SzTimeFileSnapshotMapper szTimeFileSnapshotMapper;
    @Autowired
    private SzLeaderGroupSnapshotMapper szLeaderGroupSnapshotMapper;

    @Autowired
    private SisSysOrganMapper sisSysOrganMapper;

    /**
     * 查询领导小组&密码办
     * 
     * @param groupId 领导小组&密码办主键
     * @return 领导小组&密码办
     */
    @Override
    public SzLeaderGroup selectSzLeaderGroupByGroupId(Long groupId)
    {
        return szLeaderGroupMapper.selectSzLeaderGroupByGroupId(groupId);
    }

    /**
     * 查询领导小组&密码办列表
     * 
     * @param szLeaderGroup 领导小组&密码办
     * @return 领导小组&密码办
     */
    @Override
    public List<SzLeaderGroup> selectSzLeaderGroupList(SzLeaderGroup szLeaderGroup)
    {
        return szLeaderGroupMapper.selectSzLeaderGroupList(szLeaderGroup);
    }

    /**
     * 新增领导小组&密码办
     * 
     * @param szLeaderGroup 领导小组&密码办
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSzLeaderGroup(SzLeaderGroup szLeaderGroup)
    {
        szLeaderGroup.setCreateTime(DateUtils.getNowDate());
        int rows = szLeaderGroupMapper.insertSzLeaderGroup(szLeaderGroup);
//        insertSzPersonalFile(szLeaderGroup);
        return rows;
    }

    /**
     * 修改领导小组&密码办
     * 
     * @param szLeaderGroup 领导小组&密码办
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSzLeaderGroup(SzLeaderGroup szLeaderGroup)
    {
        szLeaderGroup.setUpdateTime(DateUtils.getNowDate());
//        szLeaderGroupMapper.deleteSzPersonalFileByGroupId(szLeaderGroup.getGroupId());
//        insertSzPersonalFile(szLeaderGroup);
        return szLeaderGroupMapper.updateSzLeaderGroup(szLeaderGroup);
    }

    /**
     * 批量删除领导小组&密码办
     * 
     * @param groupIds 需要删除的领导小组&密码办主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSzLeaderGroupByGroupIds(Long[] groupIds)
    {
//        szLeaderGroupMapper.deleteSzPersonalFileByGroupIds(groupIds);
        return szLeaderGroupMapper.deleteSzLeaderGroupByGroupIds(groupIds);
    }

    /**
     * 删除领导小组&密码办信息
     * 
     * @param groupId 领导小组&密码办主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSzLeaderGroupByGroupId(Long groupId)
    {
//        szLeaderGroupMapper.deleteSzPersonalFileByGroupId(groupId);
        return szLeaderGroupMapper.deleteSzLeaderGroupByGroupId(groupId);
    }

    /**
     * 批量处理领导小组和密法办的数据
     * @param timeLine
     * @return
     */
    @Transactional
    @Override
    public int batchSzLeaderGroup(TimeLine timeLine) {
        List<SzLeaderGroup> szLeaderGroups = timeLine.getSzLeaderGroupList();
        List<SzTimeFile> szTimeFileList = timeLine.getSzTimeFileList();

        int i = 0;
        if(null != szLeaderGroups && szLeaderGroups.size() > 0) {
            List<SzLeaderGroup> idNullCollect = szLeaderGroups.stream().filter(group -> null == group.getGroupId()).collect(Collectors.toList());
            List<SzLeaderGroup> idNotNUllCollect = szLeaderGroups.stream().filter(group -> null != group.getGroupId()).collect(Collectors.toList());
            List<SzLeaderGroup> szLeaderGroupsHistory = null;
            int size = szLeaderGroupMapper.selectSzLeaderGroupList(null).size();
            if(null != idNotNUllCollect && idNotNUllCollect.size() > 0) {
                Long[] array = idNotNUllCollect.stream().map(SzLeaderGroup::getGroupId).toArray(Long[]::new);
                szLeaderGroupsHistory = szLeaderGroupMapper.selectSzLeaderGroupByGroupIds(array);
            }

            szLeaderGroupMapper.deleteSzLeaderGroup();
            setDictName(szLeaderGroups);
            szLeaderGroupMapper.batchSzLeaderGroup(szLeaderGroups);
            String fileIdCollect = null;
            if(null != szTimeFileList && szTimeFileList.size() > 0) {
                szTimeFileMapper.deleteSzTimeFile();
                szTimeFileMapper.batchSzTimeFile(szTimeFileList);
                fileIdCollect = szTimeFileList.stream().map(SzTimeFile::getFileId).map(String::valueOf).collect(Collectors.joining(","));

            }
            String groupIdCollect = szLeaderGroups.stream().map(SzLeaderGroup::getGroupId).map(String::valueOf).collect(Collectors.joining(","));

            SzTimeLine szTimeLine = new SzTimeLine();
            if(checkNumberAndNameByTwo(idNullCollect,idNotNUllCollect,size,szLeaderGroupsHistory)){

                List<SzTimeFileSnapshot> collect = szTimeFileList.stream().map(file -> {
                    SzTimeFileSnapshot fileSnapshot = new SzTimeFileSnapshot();
                    fileSnapshot.setFileContent(file.getFileContent());
                    fileSnapshot.setFileId(file.getFileId());
                    fileSnapshot.setFileName(file.getFileName());
                    fileSnapshot.setFileType(file.getFileType());
                    return fileSnapshot;
                }).collect(Collectors.toList());

                if(null != collect && collect.size() > 0) {
                    szTimeFileSnapshotMapper.batchSzTimeFileSnapshot(collect);
                }
                List<SzLeaderGroupSnapshot> collect1 = szLeaderGroups.stream().map(
                        group -> {
                            SzLeaderGroupSnapshot groupSnapshot = new SzLeaderGroupSnapshot();
                            groupSnapshot.setGroupId(group.getGroupId());
                            groupSnapshot.setGroupType(group.getGroupType());
                            groupSnapshot.setDepartment(group.getDepartment());
                            groupSnapshot.setName(group.getName());
                            groupSnapshot.setPhone(group.getPhone());
                            groupSnapshot.setPosition(group.getPosition());
                            groupSnapshot.setPositionName(group.getPositionName());
                            groupSnapshot.setRbName(group.getRbName());
                            groupSnapshot.setDeptName(group.getDeptName());
                            groupSnapshot.setSubDeptName(group.getSubDeptName());
                            groupSnapshot.setTitleName(group.getTitleName());
                            groupSnapshot.setResponsibility(group.getResponsibility());
                            groupSnapshot.setTitle(group.getTitle());
                            groupSnapshot.setSubDepartment(group.getSubDepartment());
                            return groupSnapshot;
                        }
                ).collect(Collectors.toList());

                if(null != collect1 && collect1.size() > 0) {
                    szLeaderGroupSnapshotMapper.batchSzLeaderGroupSnapshot(collect1);
                }

                String groupIdSnapshotCollect = collect1.stream().map(SzLeaderGroupSnapshot::getSnapshotId).map(String::valueOf).collect(Collectors.joining(","));
                String fileIdSnapshotCollect = collect.stream().map(SzTimeFileSnapshot::getSnapshotId).map(String::valueOf).collect(Collectors.joining(","));

                szTimeLine.setGroupIds(groupIdSnapshotCollect);
                szTimeLine.setFileIds(fileIdSnapshotCollect);
                szTimeLine.setTimeType("1");
                i = szTimeLineMapper.insertSzTimeLine(szTimeLine);

            }
            Long timeId = timeLine.getTimeId();
            if(null != timeId){
                SzTimeLine szTimeLine1 = szTimeLineMapper.selectSzTimeLineByTimeId(timeId);
                String timeType = szTimeLine1.getTimeType();
                if("0".equals(timeType)){
                    szTimeLine1.setGroupIds(groupIdCollect);
                    if(null != fileIdCollect) {
                        szTimeLine1.setFileIds(fileIdCollect);
                    }
                    szTimeLine1.setSubmissionTime(DateUtils.getNowDate());
                    i = szTimeLineMapper.updateSzTimeLine(szTimeLine1);
                }
            }else {
                SzTimeLine line  = new SzTimeLine();
                line.setTimeType("0");
                SzTimeLine szTimeLine1 = szTimeLineMapper.selectSzTimeLineList(line).stream().findFirst().orElse(null);
                if(null != szTimeLine1) {
                    szTimeLine1.setGroupIds(groupIdCollect);
                    if(null != fileIdCollect) {
                        szTimeLine1.setFileIds(fileIdCollect);
                    }
                    szTimeLine1.setSubmissionTime(DateUtils.getNowDate());
                    i = szTimeLineMapper.updateSzTimeLine(szTimeLine1);
                }else {
                    szTimeLine.setTimeType("0");
                    i = szTimeLineMapper.insertSzTimeLine(szTimeLine);
                }
            }
        }



        return i;
    }

    private void setDictName(List<SzLeaderGroup> szLeaderGroups) {
        szLeaderGroups.stream().forEach(group ->
        {
            String department = group.getDepartment();
           group.setDeptName(getDeptName(department));
            String subDepartment = group.getSubDepartment();
            group.setSubDeptName(getDeptName(subDepartment));

            String groupType = group.getGroupType();
            String position = group.getPosition();
            if(GROUP_TYPE_0.equals(groupType)) {
                if (StringUtils.isNotBlank(position)) {
                    group.setPositionName(DictUtils.getDictLabel(SZ_LEADER_JOB, position));
                }

                String title = group.getTitle();
                if (StringUtils.isNotBlank(title)) {
                    group.setPositionName(DictUtils.getDictLabel(SZ_LEADER_POSITION, title));
                }
            }else{
                if (StringUtils.isNotBlank(position)) {
                    group.setPositionName(DictUtils.getDictLabel(SZ_PASSWORD_JOB, position));
                }

                String title = group.getTitle();
                if (StringUtils.isNotBlank(title)) {
                    group.setPositionName(DictUtils.getDictLabel(SZ_PASSWORD_POSITION, title));
                }
            }

            String responsibility = group.getResponsibility();
            if(StringUtils.isNotBlank(responsibility)){
                group.setPositionName(DictUtils.getDictLabel(SZ_COMMON_DUTY,responsibility));
            }

        });
    }

    private String getDeptName(String department) {
        if(StringUtils.isNotBlank(department)){
            SisSysOrgan organ = sisSysOrganMapper.selectSisSysOrganByObjuid(department);
            if(null != organ){
                return organ.getOrgName();
            }
        }
        return "";
    }

    private boolean checkNumberAndNameByTwo(List<SzLeaderGroup> idNullCollect, List<SzLeaderGroup> idNotNUllCollect, int size, List<SzLeaderGroup> szLeaderGroupsHistory) {
        int size1 = idNotNUllCollect.size() + idNullCollect.size() ;
        if(size1 != size){
            return true;
        }
        if(null != idNullCollect && idNullCollect.size() > 0){
            return true;
        }
        if(null != idNotNUllCollect && idNotNUllCollect.size() > 0 && null != szLeaderGroupsHistory && szLeaderGroupsHistory.size() > 0){
            for (int i = 0; i < idNotNUllCollect.size(); i++) {
                if(!idNotNUllCollect.get(i).getName().equals(szLeaderGroupsHistory.get(i).getName())){
                    return true;
                }
            }

        }

        return false;
    }

    /**
     * 检查是否有数量和名字变化
     * @param szLeaderGroups
     * @return
     */
    @Override
    public boolean checkNumberAndName(List<SzLeaderGroup> szLeaderGroups) {
        AtomicBoolean flag = new AtomicBoolean(false);
        int size = szLeaderGroupMapper.selectSzLeaderGroupList(null).size();
        if(szLeaderGroups.size() != size){
            flag.set(true);
        }

        for(SzLeaderGroup group : szLeaderGroups){
            Long groupId = group.getGroupId();
            if(null == groupId){
                flag.set(true);
                break;
            }else{
                String name = group.getName();
                SzLeaderGroup szLeaderGroup = szLeaderGroupMapper.selectSzLeaderGroupByGroupId(groupId);
                if(!name.equals(szLeaderGroup.getName())){
                    flag.set(true);
                    break;
                }
            }
        }
        return flag.get();
    }


}
